package com.qsmx.core.net;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.qsmx.core.util.aes.AESUtil;
import com.qsmx.core.util.log.AtmosLogger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.WeakHashMap;

/**
 * 文 件 名:
 * 描    述:
 * 创 建 人:  Xian
 * 创建时间:  2016/7/5 0005 下午 3:28
 */
public class BaseRequestWrapper {
    private JSONObject jsonParams;

    /**
     * 基础请求封装器
     */
    public BaseRequestWrapper(JSONObject params) {
        jsonParams = new JSONObject();
        jsonParams.putAll(params);
    }

    public JSONObject signJson() {
        List<String> list = new ArrayList<>();
        for (String str : jsonParams.keySet()) {
            list.add(str);
        }
        String[] paramNames = new String[list.size()];
        paramNames = list.toArray(paramNames);
        Arrays.sort(paramNames);
        String sign = "\"";

        for (int i = 0; i < paramNames.length; i++) {
            if (!TextUtils.isEmpty((CharSequence) jsonParams.get(paramNames[i]))) {
                sign += paramNames[i] + "=" + jsonParams.get(paramNames[i]);
                if (i < paramNames.length - 1) {
                    sign += "&";
                } else {
                    sign += "\"";
                }
            }
        }

        if (sign.substring(sign.length() - 1).equals("&")) {
            sign = sign.substring(0, sign.length() - 1) + "\"";
        }

        try {
            sign = AESUtil.encrypt(sign);
            jsonParams.put("sign", sign);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParams;
    }

    public JSONObject aesJson() {
        try {
            jsonParams.put("sign", AESUtil.encrypt(jsonParams.toJSONString()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        AtmosLogger.i("json", jsonParams.toJSONString());
        return jsonParams;

    }
}
